package com.ai.service.made.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ai.common.CommonResponse;
import com.ai.common.constant.Constants;
import com.ai.common.constant.FunctionTypeConstants;
import com.ai.entity.BasePage;
import com.ai.entity.made.CoalRoutingInspectionAlarmRecord;
import com.ai.entity.made.CoalRoutingInspectionAlarmRecordInfo;
import com.ai.entity.made.RegionBase;
import com.ai.entity.made.camera.CameraPO;
import com.ai.mapper.made.CoalRoutingInspectionAlarmRecordMapper;
import com.ai.model.page.CoalRoutingInspectionPage;
import com.ai.model.vo.CoalRoutingInspectionAlarmRecordVo;
import com.ai.model.vo.CoalRoutingInspectionAlarmVo;
import com.ai.service.made.*;
import com.ai.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiaok
 * @since 2024-10-29
 */
@Service
@Slf4j
public class CoalRoutingInspectionAlarmRecordServiceImpl extends ServiceImpl<CoalRoutingInspectionAlarmRecordMapper, CoalRoutingInspectionAlarmRecord> implements ICoalRoutingInspectionAlarmRecordService {


    @Resource
    private ICoalRoutingInspectionAlarmRecordInfoService iCoalRoutingInspectionAlarmRecordInfoService;

    @Resource
    IRegionManageService iRegionManageService;

    @Resource
    IRegionBaseService iRegionBaseService;

    @Resource
    private CameraService cameraService;


    @Resource
    private ICoalRoutingInspectionService iCoalRoutingInspectionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse addAlarm(CoalRoutingInspectionAlarmVo coalRoutingInspectionAlarmVo) {

        //修改巡检告警记录信息
        String inspectSid = coalRoutingInspectionAlarmVo.getInspectSid();
        if (org.apache.commons.lang3.StringUtils.isBlank(inspectSid)){
            throw new RuntimeException("巡检uuid不能为空");
        }

        CoalRoutingInspectionAlarmRecord inspectionAlarmRecord = this.getOne(new QueryWrapper<CoalRoutingInspectionAlarmRecord>()
                .eq("inspect_sid", inspectSid));

        if (null == inspectionAlarmRecord){
            //说明是该巡检是第一次进行
            inspectionAlarmRecord = new CoalRoutingInspectionAlarmRecord();
            BeanUtils.copyProperties(coalRoutingInspectionAlarmVo,inspectionAlarmRecord);
            inspectionAlarmRecord.setCreateTime(LocalDateTime.now());
            inspectionAlarmRecord.setCreateUser(Constants.ALGORITHM_SYSTEM);

            inspectionAlarmRecord.setUpdateUser(Constants.ALGORITHM_SYSTEM);

            //获取基本的摄像头信息
            CameraPO cameraPO = cameraService.getById(coalRoutingInspectionAlarmVo.getCameraId());
            if (ObjectUtil.isEmpty(cameraPO)){
                throw new RuntimeException("cameraId对应的摄像头不存在，请检查后重新发送");
            }
            inspectionAlarmRecord.setCameraCode(cameraPO.getCode());
            inspectionAlarmRecord.setCameraId(coalRoutingInspectionAlarmVo.getCameraId());

            if (coalRoutingInspectionAlarmVo.getIsFinalReq()){
                try {
                    inspectionAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(coalRoutingInspectionAlarmVo.getRoutingEndTime()));
                }catch (Exception e){
                    log.error("===========================  巡检第一次即为最后一次告警推送，获取当前轮次巡检结束时间失败  ===========================");
                    inspectionAlarmRecord.setUpdateTime(LocalDateTime.now());
                    e.printStackTrace();
                }
            }else {
                inspectionAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(coalRoutingInspectionAlarmVo.getInspectEndTime()));
            }

            //更新巡检的状态


            //进行数据库新增操作
            this.save(inspectionAlarmRecord);
        }else {
            //更新当前检测的巡检状态
            inspectionAlarmRecord.setInspectState(coalRoutingInspectionAlarmVo.getInspectState());
            inspectionAlarmRecord.setSequence(coalRoutingInspectionAlarmVo.getSequence());
            inspectionAlarmRecord.setUpdateUser(Constants.ALGORITHM_SYSTEM);
            if (coalRoutingInspectionAlarmVo.getIsFinalReq()){
                try {
                    //存在巡检详情
                    String finalDate = iCoalRoutingInspectionAlarmRecordInfoService.getFinalDate(inspectionAlarmRecord.getId());
                    String endTime =  iCoalRoutingInspectionService.getRoutingEndTimeStr(coalRoutingInspectionAlarmVo.getCameraId(),
                            FunctionTypeConstants.INSPECTION_TRAJECTORY,coalRoutingInspectionAlarmVo.getSequence());



                    inspectionAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(finalDate+" "+endTime));
                }catch (Exception e){
                    log.error("===========================  获取巡检详情失败,使用当前时间作为最终的巡检时间  ===========================");
                    inspectionAlarmRecord.setUpdateTime(LocalDateTime.now());
                    e.printStackTrace();
                }
            }else {
                inspectionAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(coalRoutingInspectionAlarmVo.getInspectEndTime()));
            }
            //更新本轮巡检的状态



            this.updateById(inspectionAlarmRecord);
            if (coalRoutingInspectionAlarmVo.getIsFinalReq()){
                return CommonResponse.ok("巡检告警接收成功");
            }
        }


        if (!coalRoutingInspectionAlarmVo.getIsFinalReq()){
            //开始新增巡检对应的详细信息
            CoalRoutingInspectionAlarmRecordInfo coalRoutingInspectionAlarmRecordInfo = new CoalRoutingInspectionAlarmRecordInfo();
            BeanUtils.copyProperties(coalRoutingInspectionAlarmVo,coalRoutingInspectionAlarmRecordInfo);
            coalRoutingInspectionAlarmRecordInfo.setInspectBeginTime(DateUtil.parseLocalDateTime(coalRoutingInspectionAlarmVo.getInspectBeginTime()));
            coalRoutingInspectionAlarmRecordInfo.setInspectEndTime(DateUtil.parseLocalDateTime(coalRoutingInspectionAlarmVo.getInspectEndTime()));
            coalRoutingInspectionAlarmRecordInfo.setInspectAlarmRecordId(inspectionAlarmRecord.getId());
            coalRoutingInspectionAlarmRecordInfo.setUpdateTime(LocalDateTime.now());
            coalRoutingInspectionAlarmRecordInfo.setUpdateUser(Constants.ALGORITHM_SYSTEM);
            coalRoutingInspectionAlarmRecordInfo.setCreateTime(LocalDateTime.now());
            coalRoutingInspectionAlarmRecordInfo.setCreateUser(Constants.ALGORITHM_SYSTEM);
            iCoalRoutingInspectionAlarmRecordInfoService.save(coalRoutingInspectionAlarmRecordInfo);
        }

        return CommonResponse.ok("巡检告警接收成功");
    }

    @Override
    public CommonResponse coalRoutingInspectionList(CoalRoutingInspectionPage coalRoutingInspectionPage) {

        BasePage<CoalRoutingInspectionAlarmRecordVo> resPage = new BasePage<>();

        List<String> cameraIdList = new ArrayList<>();
        if (StrUtil.isNotEmpty(coalRoutingInspectionPage.getRegionBaseId())){
            //获取其组织下的所有摄像头id
            cameraIdList = iRegionManageService.getBelowCameraIdList(coalRoutingInspectionPage.getRegionBaseId());
        }else {
            //获取当前登录用户下的所有设摄像头id
            cameraIdList = iRegionManageService.getBelowCameraIdList(SecurityUtils.getLoginRegionBaseId());
        }
        if (CollectionUtils.isEmpty(cameraIdList)){
            //当前区域没有管理任何摄像头
            return CommonResponse.ok(resPage);
        }

        coalRoutingInspectionPage.setCameraIdList(cameraIdList);

        //获取当前区域管理的摄像头
//        HashMap<String,String> cameraRegionMap = SecurityUtils.getRegionManageCamerasCode(iRegionBaseService, iRegionManageService);
//        if (CollectionUtils.isEmpty(cameraRegionMap)){
//            //当前区域没有管理任何摄像头
//            return CommonResponse.ok(coalRoutingInspectionPage);
//        }
//        //获取所有摄像头code
//        if (StringUtils.isEmpty(coalRoutingInspectionPage.getRegionBaseId())) {
//            ArrayList<String> cameraCodes = new ArrayList<>(cameraRegionMap.keySet());
//            coalRoutingInspectionPage.setCameraCodes(cameraCodes);
//        }else{
//            CommonResponse bindList = iRegionManageService.getBindList(coalRoutingInspectionPage.getRegionBaseId());
//            ArrayList<String> bindListData = (ArrayList<String>) bindList.getData();
//            coalRoutingInspectionPage.setCameraCodes(bindListData);
//        }
//        log.info("===========================  cameraCodes  ===========================,{}",coalRoutingInspectionPage.getCameraCodes());

        QueryWrapper<CoalRoutingInspectionAlarmRecord> queryWrapper = new QueryWrapper<>();
        QueryWrapper<CoalRoutingInspectionAlarmRecord> recordQueryWrapper = coalRoutingInspectionPage.getQuery(queryWrapper);
        CoalRoutingInspectionPage routingInspectionPage = page(coalRoutingInspectionPage, recordQueryWrapper);

        List<CoalRoutingInspectionAlarmRecord> records = routingInspectionPage.getRecords();

        LinkedList<CoalRoutingInspectionAlarmRecordVo> recordVoLinkedList = new LinkedList<>();
        for (CoalRoutingInspectionAlarmRecord inspectionAlarmRecord : records) {

            CoalRoutingInspectionAlarmRecordVo coalRoutingInspectionAlarmRecordVo = new CoalRoutingInspectionAlarmRecordVo();
            BeanUtils.copyProperties(inspectionAlarmRecord,coalRoutingInspectionAlarmRecordVo);

            CameraPO cameraPO = cameraService.getById(inspectionAlarmRecord.getCameraId());
            RegionBase regionBase = iRegionBaseService.getById(cameraPO.getRegionId());
            coalRoutingInspectionAlarmRecordVo.setRegionName(regionBase.getRegionName());
            coalRoutingInspectionAlarmRecordVo.setCameraNickname(cameraPO.getNickname());

            recordVoLinkedList.add(coalRoutingInspectionAlarmRecordVo);
        }
        BeanUtils.copyProperties(routingInspectionPage,resPage);
        resPage.setRecords(recordVoLinkedList);


        return CommonResponse.ok(resPage);
    }
}
